package top.eggcode.modules.monitor.control;

import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import top.eggcode.common.mvc.Result;
import top.eggcode.common.mvc.ResultWrapper;
import top.eggcode.modules.monitor.common.Metrics;
import top.eggcode.modules.monitor.model.MetricUpload;
import top.eggcode.modules.monitor.model.MetricUsage;
import top.eggcode.modules.monitor.model.MetricUsageBiz;
import top.eggcode.modules.monitor.store.MetricUsageStore;
import top.eggcode.base.PackBaseController;

import java.util.List;
import java.util.UUID;

/**
 * Title: 主机配置
 * Description: TODO
 * Date: 2021/9/23 21:21
 *
 * @author JiaQi Ding
 * @version 1.0
 */
@AllArgsConstructor
@RequestMapping("/api/monitor/hosts")
@RestController
public class HostController extends PackBaseController {

    private final MetricUsageStore metricUsageStore;

    /**
     * 生成唯一标识
     *
     * @return 数据
     */
    @PostMapping("/id/create")
    public Result<?> createId() {
        String instanceId = UUID.randomUUID().toString();

        return pack(instanceId);
    }

    /**
     * 指标上报
     *
     * @return
     */
    @PostMapping("/metrics/upload")
    public Result<?> metricReport(@RequestBody MetricUpload param) {

        List<MetricUsageBiz> usages = param.getUsages();

        usages.forEach(item -> {
            String metricCode = Metrics.getCode(item.getName());
            String value = item.getValue();
            MetricUsage usage = new MetricUsage();
            usage.init();
            usage.setInstanceId(param.getInstanceId());
            usage.setMetricId(metricCode);
            usage.setValue(value);
            metricUsageStore.save(usage);
        });
        return ResultWrapper.successful();
    }


}
